package com.soup.utils;

import com.soup.config.SystemConfiguration;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class SQLUtils {

    private static Map<Class,String> map = new HashMap<>();

    static {
        map.put(Integer.class,"int");
        map.put(Float.class,"float");
        map.put(Double.class,"double");
        map.put(int.class,"int");
        map.put(float.class,"float");
        map.put(double.class,"double");
        map.put(String.class,"varchar");
    }

    public static String objectToCreateSQL(Class<?> cls){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("CREATE TABLE ");
        stringBuffer.append(cls.getSimpleName().toLowerCase() + " ");
        stringBuffer.append("(");
        Field[] fields = cls.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            stringBuffer.append(fields[i].getName() + " " + map.get(fields[i].getType()));
            stringBuffer.append("("+getSQLTypeLength(fields[i].getType())+"),");
        }

        return stringBuffer.replace(stringBuffer.lastIndexOf(","),stringBuffer.length(),")").toString();
    }

    public static int getSQLTypeLength(Class<?> cls){
        return Integer.parseInt(SystemConfiguration.getProperty("base."+map.get(cls)));
    }
}
